package org.ze.chatbot.api.application.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.ze.chatbot.api.domain.ai.IOpenAI;
import org.ze.chatbot.api.domain.blbl.IBlblApi;
import org.ze.chatbot.api.domain.blbl.model.aggregates.UnAnsweredQuestionsAggregates;
import com.alibaba.fastjson.JSON;
import org.ze.chatbot.api.domain.blbl.model.vo.reqvo.Replies;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
@EnableScheduling
@Configuration
public class ChatbotSchedule {

    private Logger logger = LoggerFactory.getLogger(ChatbotSchedule.class);

    @Value("${chatbot-api.oid}")
    private String oid;
    @Value("${chatbot-api.cookie}")
    private String cookie;
    @Value("${chatbot-api.openAiKey}")
    private String openAiKey;

    @Resource
    private IBlblApi blblApi;
    @Resource
    private IOpenAI openAI;

    @Scheduled(cron = "0/30 * * * * ?")
    public void run() {
        try {
            if (new Random().nextBoolean()) {
                logger.info("{} 随机打烊中...");
                return;
            }

            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour > 24 || hour < 6) {
                logger.info("{} 打烊时间不工作，AI 下班了！");
                return;
            }

            // 1. 检索问题
            UnAnsweredQuestionsAggregates unAnsweredQuestionsAggregates = blblApi.queryUnAnsweredQuestionsRpid(oid, cookie);
            logger.info("测试结果：{}", JSON.toJSONString(unAnsweredQuestionsAggregates));
            List<Replies> replies = unAnsweredQuestionsAggregates.getReplies();

            replies.removeIf(Replies -> Replies.getRcount()>0);

            if (null == replies || replies.isEmpty()) {
                logger.info("{} 本次检索未查询到待回答问题");
                return;
            }
            // 2. AI 回答
            Replies reply = replies.get(replies.size() - 1);
            String answer = openAI.doChatGPT(openAiKey, reply.getContent().getMessage().trim());

            // 3. 问题回复
            String parent = String.valueOf(reply.getRpid());
            String message = reply.getContent().getMessage();
            String status = blblApi.answer(cookie,answer,oid,parent);
            logger.info("编号：{} 问题：{} 回答：{} 状态：{}", reply.getRpid(), message, answer, status);
        } catch (Exception e) {
            logger.error("{} 自动回答问题异常", e);
        }
    }

}
